package server

import (
	"encoding/xml"
	"log"
	"net/http"
	"regexp"
	"strings"

	"github.com/labstack/echo"
	"go.uber.org/zap"
)

// WebReturn  web return
type WebReturn struct {
	Value   interface{} `json:"data"`
	Success bool        `json:"success"`
	Message string      `json:"message"`
	Code    int         `json:"code"`
}

// http://localhost:8800/update/alert?appids=2&target_type=1
func webServer() {
	e := echo.New()

	e.GET("/search/novel", searchNovel)

	err := e.Start(Conf.Listen.WebAddr)
	if err != nil {
		Logger.Fatal("echo", zap.Error(err))
	}
}

// var atagRegExp = regexp.MustCompile(`<div[^>]+[(href)|(HREF)]\s*\t*\n*=\s*\t*\n*[(".+")|('.+')][^>]*>[^<]*</div>`)

var REG_BODY = regexp.MustCompile(`/<body[^>]*>([\s\S]*)<\/body>/`)

var atagRegExp = regexp.MustCompile(`<a[^>]+[(href)|(HREF)]\s*\t*\n*=\s*\t*\n*[(".+")|('.+')][^>]*>[^<]*</a>`)

var (
	ptnIndexItem    = regexp.MustCompile(`<a target="_blank" href="(.+\.html)" title=".+" >(.+)</a>`)
	ptnContentRough = regexp.MustCompile(`(?s).*<div class="artcontent">(.*)<div id="zhanwei">.*`)
	ptnBrTag        = regexp.MustCompile(`<br>`)
	ptnHTMLTag      = regexp.MustCompile(`(?s)</?.*?>`)
	ptnSpace        = regexp.MustCompile(`(^\s+)|( )`)
)

func searchNovel(c echo.Context) error {
	// 小说名
	novel := c.QueryParam("novel")
	if novel == "" {
		return c.JSON(http.StatusOK, newWebReturn("", false, "unfind novel", 0))
	}

	body, err := gNovels.NovelsSer.search(novel)
	if err != nil {
		Logger.Warn("search", zap.Error(err))
		return err
	}

	atag := atagRegExp.FindAllString(string(body), -1)
	for _, a := range atag {
		log.Println(a)
		// href, _ := GetHref(a)
		// log.Println(href)
		// if strings.Contains(href, "article/details/") {
		// 	fmt.Println("☆", href)
		// } else {
		// 	fmt.Println("□", href)
		// }

	}

	// ioutil.WriteFile("novels.text", body, 0644)

	return c.JSON(http.StatusOK, newWebReturn(string(body), true, "", 0))
}

func newWebReturn(value interface{}, success bool, msg string, code int) *WebReturn {
	return &WebReturn{
		Value:   value,
		Success: success,
		Message: msg,
		Code:    code,
	}
}

func GetHref(atag string) (href, content string) {
	inputReader := strings.NewReader(atag)
	decoder := xml.NewDecoder(inputReader)
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch token := t.(type) {
		// 处理元素开始（标签）
		case xml.StartElement:
			for _, attr := range token.Attr {
				attrName := attr.Name.Local
				attrValue := attr.Value
				if strings.EqualFold(attrName, "href") || strings.EqualFold(attrName, "HREF") {
					href = attrValue
				}
			}
		// 处理元素结束（标签）
		case xml.EndElement:
		// 处理字符数据（这里就是元素的文本）
		case xml.CharData:
			content = string([]byte(token))
		default:
			href = ""
			content = ""
		}
	}
	return href, content
}
